﻿using System;
using System.Diagnostics;
using System.Net;
using System.Web;
using AspNetInfo.Core;
using System.Data;

namespace AspNetInfo.Detectors
{
    public class EnvironmentDetector : IDetector
    {
        public DataTable Detect(EnvironmentPermissions permissions)
        {
            //EnvironmentPermissions restricts access in medium trust environment to:
            //TEMP,TMP,USERNAME,OS,COMPUTERNAME
            var dt = DetectorHelper.MakeResultTable();
            dt.Rows.Add("Host Name", Dns.GetHostEntry(Dns.GetHostName()).HostName);
            dt.Rows.Add("IP", Dns.GetHostAddresses(Dns.GetHostName())[0].ToString());
            if (permissions.TrustLevel > AspNetHostingPermissionLevel.Medium)
            {
                dt.Rows.Add("OS Version", Environment.OSVersion.ToString());
                dt.Rows.Add("Processor Count", Environment.ProcessorCount.ToString());
                dt.Rows.Add("Username", String.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName));
                dt.Rows.Add("Uptime", GetEnvironmentUptime());
                dt.Rows.Add("Server Date & Time", DateTime.Now.ToString());
            }

            string processName = "n/a";
            try
            {
                // late binding so that LinkDemands are not triggered
                object currentProcess = typeof(Process).GetMethod("GetCurrentProcess", Type.EmptyTypes).Invoke(null, null);
                object processModule = typeof(Process).GetProperty("MainModule").GetValue(currentProcess, null);
                processName = (string)typeof(ProcessModule).GetProperty("ModuleName").GetValue(processModule, null);
                dt.Rows.Add("Worker process", processName);
            }
            catch { } // swallow exceptions


            return dt;
        }
        public string Name
        {
            get { return "Environment"; }
        }
        // http://www.4guysfromrolla.com/articles/020402-1.aspx
        public static string GetEnvironmentUptime()
        {
            TimeSpan ts = TimeSpan.FromMilliseconds(Environment.TickCount);
            int minutesUp = ts.Minutes;
            int hoursUp = ts.Hours;
            int daysUp = ts.Days;

            return ts.Days + " days, " + ts.Hours + " hours, " + "and " + ts.Minutes + " minutes.";
        }

        public string Description
        {
            get { return string.Empty; }
        }

        public string TabName
        {
            get { return Tabs.General; }
        }
    }
}
